<template>
  <div class="wrap">
    <div class="content" v-loading="loading">
      <el-form
        :model="currentForm"
        ref="form"
        label-width="150px"
        label-suffix=":"
        label-position="left"
        :rules="rules"
      >
        <div class="form-warehouseName">
          <el-form-item label="仓库名" label-width="100px" class="font-bold" prop="warehouseName">
            <el-input
              v-model="currentForm.warehouseName"
              autocomplete="off"
              style="width: 300px"
            ></el-input>
          </el-form-item>
        </div>


        <div class="form-box">
          <div class="form-title">收货地址：</div>
          <el-form-item label="收货人姓名" prop="address.fullName" >
            <el-input v-model="currentForm.address.fullName" placeholder="请填写收货人姓名"></el-input>
          </el-form-item>

          <el-form-item label="手机号" prop="address.mobile">
            <el-input v-model="currentForm.address.mobile" placeholder="请填写手机号"></el-input>
          </el-form-item>

          <el-form-item label="电话" prop="address.phone">
            <el-input v-model="currentForm.address.phone" placeholder="请填写电话"></el-input>
          </el-form-item>

          <el-form-item label="邮编" prop="address.postCode">
            <el-input v-model="currentForm.address.postCode" placeholder="请填写邮编"></el-input>
          </el-form-item>


          <el-form-item label="所在地区" prop="address.areaText">
            <el-select v-model="currentForm.address.provinceText" class="mgr10" filterable placeholder="请选择省份" @change="handleSelectProvinceText">
              <el-option
                v-for="(item,key) in provinceList"
                :key="key"
                :label="item"
                :value="item">
              </el-option>
            </el-select>

            <el-select v-model="currentForm.address.cityText" filterable placeholder="请选择市区" @change="handleSelectCityText" class="mgr10">
              <el-option
                v-for="(item,key) in cityList"
                :key="key"
                :label="item"
                :value="item">
              </el-option>
            </el-select>

            <el-select v-model="currentForm.address.areaText" filterable placeholder="请选择县/镇" >
              <el-option
                v-for="(item,key) in areaList"
                :key="key"
                :label="item"
                :value="item">
              </el-option>
            </el-select>


          </el-form-item>

          <el-form-item label="详细地址" prop="address.address">
            <el-input type="textarea" v-model="currentForm.address.address" placeholder="请填写详细地址"></el-input>
          </el-form-item>

        </div>



        <div class="form-box" v-if="false">
          <div class="form-title">{{ $t('setting.添加货件设置') }}：</div>
          <el-form-item :label="$t('table.货箱类型')">
            <el-radio-group v-model="currentForm.shipmentTableType">
              <el-radio :label="1">{{ $t('setting.整箱和混箱') }}</el-radio>
              <el-radio :label="2">{{ $t('setting.仅整箱') }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <div class="form-content">
            <span class="append-price-tips">{{ $t('setting.整箱为一个货件箱一个SKU，混箱支持一个货件箱多个SKU') }}</span>
          </div>
        </div>

        <div class="form-box" v-if="currentForm.id">
          <div class="form-title">量方机：</div>
          <el-button type="primary" icon="el-icon-plus" @click="showMachineDialog(null)">新增量方机</el-button>
          <div class="table mgt20">
            <el-table
              border
              style="width: 600px"
              :data="machineList"
            >
              <el-table-column
                prop="machineName"
                label="机器名称"
                align="center"
                min-width="150"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                prop="type"
                label="量方机类型"
                align="center"
                min-width="100"
              >
                <template v-slot="{row}">
                  {{getTypeName(row.type)}}
                </template>
              </el-table-column>
              <el-table-column
                prop="op"
                label="操作"
                align="center"
                min-width="200"
              >
                <template v-slot="{row}">
                  <el-button type="primary" @click="copyUrl(row)">复制链接</el-button>
                  <el-button type="primary" @click="showMachineDialog(row)">编辑</el-button>
                  <el-button type="danger" @click="delMachine(row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <el-button @click="back">{{$t('common.back')}}</el-button>
        <el-button type="primary" :disabled="disableButton" @click="saveData" :loading="saveLoading">{{ $t('common.confirm') }}</el-button>
      </el-form>
    </div>
    <el-dialog
      :title="machineForm.code ? '编辑量方机' : '新增量方机'"
      :visible.sync="machineDialog"
    >
      <el-form label-width="100px">
        <el-form-item label="机器名称" prop="machineName">
          <el-input v-model="machineForm.machineName" placeholder="仅用于方便记忆处理操作，不填系统则随机生成一个名称"></el-input>
        </el-form-item>
        <el-form-item label="量方机类型" prop="type">
          <el-select v-model="machineForm.type">
            <el-option
              v-for="item in machineTypeList"
              :key="item.label"
              :label="item.text"
              :value="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitMachine" :loading="machineLoading">确认</el-button>
          <el-button @click="machineDialog = false;">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import {
  deepCopy,
  getFalabellaName,
  getMercadoName,
  getShopeeName,
  getSheinName,
  getAmazonName,
  getTikTokName,
  copyToClipboard
} from "@/utils";
import {getSetting, saveSetting} from "@/api/setting";
import {getAppName} from "@/utils/settings";
import {getWareHouseName} from "@/utils/common";
import GoodsSizePriceMixin from "@/views/setting/mixin/GoodsSizePriceMixin";
import MiddlePriceMixin from "@/views/setting/mixin/MiddlePriceMixin";
import ShipmentPriceMixin from "@/views/setting/mixin/ShipmentPriceMixin";
import TransferFeeListMixin from "@/views/setting/mixin/TransferFeeListMixin";
import {getWarehouseInfo, saveWarehouse} from "@/api/warehouse";
import LogisticTypePriceMixin from "@/views/setting/mixin/LogisticTypePriceMixin";
import GoodsSizePrice from "@/views/warehouse/components/GoodsSizePrice.vue";
import StorageWeightRange from "@/views/warehouse/components/StorageWeightRange.vue";
import StorageWeightRangeMixin from "@/views/warehouse/mixin/StorageWeightRangeMixin";
import areaData from "china-area-data/data";
import {getPropByPath} from "element-ui/src/utils/util";
import request from "@/utils/request";



export default {
  name: "index",
  components: {},
  mixins: [],
  data(){
    return {
      currentForm: {
        id: 0,
        address: {
          fullName: '', // 收货人姓名
          phone: '', // 联系方式
          postCode: '', // 邮编
          provinceText: '', // 省
          cityText: '', // 市
          areaText: '', // 区 ？
          townText: '', // 镇 ？
          address: '', // 详细地址
        },
        shipmentTableType: 1,
      },
      copyForm: {}, // 用于对比是否有数据变化
      loading: false,
      saveLoading: false,
      rules:{
        warehouseName: [
          { required: true, message:this.$t('common.pleaseFillIn'), trigger: 'blur' },
        ],
        'address.fullName': [{ required: true, trigger: 'blur', message: '请填写收货人姓名' }],
        'address.mobile': [
          { required: true, trigger: 'blur', message: '请填写手机号' },
          // { pattern: /^1[3-9]\d{9}$/ , message: '手机号格式有误',trigger: 'blur' },
        ],
        'address.phone': [
          { required: true, trigger: 'blur', message: '请填写电话' },
          // { pattern: /^(1[3-9]\d{9}|0\d{2,3}-?\d{7,8})$/ , message: '电话格式有误',trigger: 'blur' },
        ],
        'address.postCode': [{ required: true, trigger: 'blur', message: '请填写邮编' }],
        'address.areaText': [{ required: true, trigger: 'change', message: '请填写所在地区' }],
        'address.address': [{ required: true, trigger: 'blur', message: '请填写详细地址' }],

      },
      areaData,
      provinceList: {},
      cityList: {},
      areaList: {},
      areaCode:{
        province: '',
        city: '',
        area: '',
      },
      machineDialog: false,
      machineForm: {
        code: '',
        machineName: '',
        type: 'MJ',
      },
      machineTypeList: [
        {label: 'MJ', text: '墨家量方机', },
        {label: 'JH', text: '几何量方机', }
      ],
      machineLoading: false,
      machineList: [],
    }
  },
  created() {
    this.provinceList = this.areaData['86']
    this.currentForm.id = this.$route.query.id
    this.setCopyForm()
    this.getData();
    this.getMachineList();
  },
  computed:{
    disableButton(){
      return JSON.stringify(this.currentForm) === JSON.stringify(this.copyForm)
    },
  },
  methods: {
    objEquals(obj1, obj2){
      return JSON.stringify(obj1) === JSON.stringify(obj2)
    },
    setCopyForm(){
      this.copyForm = deepCopy(this.currentForm)
    },
    getData(){
      if(!this.currentForm.id){
        return
      }
      this.loading = true;
      request({
        url: `/warehouse/flWarehouse/` + this.currentForm.id
      })
        .then(res=>{
          this.loading = false
          this.currentForm = deepCopy(res.data)
          this.setCopyForm()
        })
    },

    saveData(){
      this.$refs.form.validate(valid => {
        if(valid){
          request({
            url: '/warehouse/saveFlWarehouse',
            method: 'post',
            data: this.currentForm,
          })
            .then(res=>{
              this.$successMessage(res.message)
              this.setCopyForm()
            })
        }
      })
    },
    back(){
      this.$router.go(-1)
    },
    // 选择了省份
    handleSelectProvinceText(removeData = true){
      let provinceText = this.currentForm.address.provinceText
      if(removeData){
        this.currentForm.address.cityText = ''
        this.currentForm.address.areaText = ''
        this.cityList = {}
        this.areaList = {}
      }
      // 找到对应的code
      this.areaCode.province = ''
      for (const provinceListKey in this.provinceList) {
        if(this.provinceList[provinceListKey] === provinceText){
          this.areaCode.province = provinceListKey
          break;
        }
      }
      // 设置对应的市值
      this.cityList = deepCopy(this.areaData[this.areaCode.province])
      // 如果只有一个直接赋值
      if(Object.keys(this.cityList).length === 1){
        for (const cityListElement in this.cityList) {
          this.currentForm.address.cityText = this.cityList[cityListElement]
          this.handleSelectCityText()
        }
      }
    },
    // 选择了市级
    handleSelectCityText(removeData = true){
      let cityText = this.currentForm.address.cityText;
      if(removeData){
        this.currentForm.areaText = '';
        this.areaList = {}
      }

      // 找到对应的code
      this.areaCode.city = ''
      for (const cityListKey in this.cityList) {
        if(this.cityList[cityListKey] === cityText){
          this.areaCode.city = cityListKey
          break;
        }
      }

      this.areaList = deepCopy(this.areaData[this.areaCode.city])

    },
    showMachineDialog(row = null){
      this.machineDialog = true
      if(!row){
        this.machineForm.code = ''
        this.machineForm.machineName = ''
        this.machineForm.type = 'MJ'
      }else{
        this.machineForm.code = row.code
        this.machineForm.machineName = row.machineName
        this.machineForm.type = row.type
      }
      console.log(this.machineForm.type)
    },
    submitMachine(){
      this.machineLoading = true
      const data = deepCopy(this.machineForm)
      data.flWarehouseId = this.currentForm.id
      request({
        url: '/warehouse/saveMachine',
        method: 'put',
        data,
      })
        .then(res=>{
          this.machineLoading = false
          this.$successMessage(res.message)
          this.machineDialog = false
          this.getMachineList()
        })
    },
    getMachineList(){
      const params = {
        flWarehouseId: this.currentForm.id
      }
      request({
        url: '/warehouse/getMachineList',
        params
      })
        .then(res=>{
          this.machineList = res.data
        })
    },
    getTypeName(type){
      const obj = this.machineTypeList.find(item=> item.label === type)
      return obj?.text || ''
    },
    copyUrl(row){
      if(!row.url){
        return;
      }
      copyToClipboard(row.url)
      this.$successMessage('复制成功')
    },
    delMachine(row){
      this.$confirm('确定要删除这条数据吗？', '删除数据',{
        type: 'warning'
      })
        .then(()=>{
          request({
            url: `/warehouse/delMachine/${row.code}`,
            method: 'delete',
          })
            .then((res)=>{
              this.$successMessage(res.message)
              this.getMachineList()
            })
        })
        .catch(()=>{})
    },
  },
  // 路由跳转离开提示
  beforeRouteLeave(to,from,next){
    if(!this.disableButton){
      setTimeout(()=>{
        this.$warning('',{
          title: this.$t('setting.当前信息未保存，确认离开？'),
        }).then(()=>{
          next();
        }).catch(() => {
          next(false);
        })
      },0)
    }else{
      next()
    }
  },
}
</script>
<style>
.form-box{
  .el-form-item__label{
    color: #000000;
    font-weight: bold;
    font-size: 15px;
  }
}
.form-warehouseName{
  .el-form-item__label{
    color: #000000;
    font-weight: bold;
    font-size: 15px;
  }
}
</style>

<style scoped lang="scss">
.wrap {
  padding: 10px 30px;
  .header{
    display: flex;
    justify-content: space-between;
  }
  .content{
    padding: 20px 0 0;
    .header-tips{
      font-size: 14px;
    }
    .form{
      margin-top: 30px;
    }
  }
  .form-box{
    border-radius: 2px;
    border: 1px solid #f2f2f2;
    padding: 15px 20px;
    margin-bottom: 20px;
    .form-title{
      font-weight: bold;
      font-size: 18px;
      //color: #ff0000;
      margin-bottom: 10px;
    }
    .header-tips{
      font-weight: 500;
      color: #FF0000;
    }
    .form-content{
      display: flex;
      flex-direction: row;
      align-items: flex-start;
      .price-box{
        border-radius: 2px;
        border: 1px solid #f2f2f2;
        padding: 15px 20px;
        width: 500px;
        margin-top: 20px;
        margin-right: 50px;
        .price-title{
          font-weight: bold;
          font-size: 14px;
          color: #409EFF;
          margin-bottom: 10px;
        }
      }
      .middle-box{
        border-radius: 2px;
        border: 1px solid #f2f2f2;
        padding: 15px 20px;
        width: 1200px;
        margin-top: 20px;
        margin-right: 50px;
        .title{
          font-weight: bold;
          font-size: 14px;
          color: #409EFF;
          margin-bottom: 10px;
        }
        .middle-content{
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          .middle-left{
            width: 50%;
          }
          .middle-right{
            width: 50%;
          }
        }
        .middle-price-content{
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          .weight{
            width: 50%;
          }
          .price{
            width: 50%;
          }
        }

      }
      .tallying-box{
        border-radius: 2px;
        border: 1px solid #f2f2f2;
        padding: 15px 20px;
        width: 1200px;
        margin-top: 20px;
        margin-right: 50px;
        .title{
          font-weight: bold;
          font-size: 14px;
          color: #409EFF;
          margin-bottom: 10px;
        }
        .tallying-content{
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          .tallying-left{
            width: 50%;
          }
          .tallying-right{
            width: 50%;
          }
          .tallying-price-content{
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            .weight{
              width: 50%;
            }
            .price{
              width: 50%;
            }
          }
        }
      }
      .goods-size-price{
        width: 1000px;
        .goods-size-price-content{
          display: flex;
          flex-direction: row;
          margin-bottom: 10px;
          align-items: center;
          justify-content: flex-start;
          .weight{
            width: 220px;
          }
          .cal-type{
            width: 180px;
          }
          .PSC-first{
            width: 200px;
          }
          .PSC-append{
            width: 200px;
          }
          .remove-item{
            width: 50px;
          }
        }
      }
      .logistic-type{
        width: 1000px;
        .logistic-type-content{
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          margin-bottom: 10px;
          font-size: 14px;
          color: #7f7f7f;
          font-weight: bold;
          .weight{
            width: 200px;
          }
          .PSC-first{
            width: 200px;
          }
          .PSC-append{
            width: 250px;
          }
        }
      }
      .append-price-tips{
        font-size: 12px;
        color: #7F7F7F;
      }
      .storage-box{
        border-radius: 2px;
        border: 1px solid #f2f2f2;
        padding: 15px 20px;
        width: 1000px;
        margin-top: 20px;
        .title{
          font-weight: bold;
          font-size: 14px;
          color: #409EFF;
          margin-bottom: 10px;
        }
        .storage-content{

        }
      }
    }
  }
}

</style>
